package com.yongchun.controller;

import com.yongchun.commons.StringUtil;
import com.yongchun.config.TokenVO;
import com.yongchun.config.adapay.AdapayItemConfig;
import com.yongchun.config.adapay.AdapayUtil;
import com.yongchun.model.Player;
import com.yongchun.pubInter.SkException;
import com.yongchun.pubInter.SkJsonResult;
import com.yongchun.service.IPlayerService;
import com.yongchun.vo.SignatureVO;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;


/**
 * @author afeng
 * @version 1.0
 * @date 2023/11/15 下午5:03
 */
@Controller
@RequestMapping("/auth/")
public class AuthController{
    @Autowired
    private IPlayerService playerService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private AdapayUtil adapayUtil;
    @RequestMapping("yongCun")
    public String ycAuth(HttpServletRequest request) {
        String code = request.getParameter("code");
        System.out.println(code);
        return "ycPay";
    }

    @RequestMapping("suNing")
    public String suNing(HttpServletRequest request) {
        String code = request.getParameter("code");
        System.out.println(code);
        return "suNinPay";
    }

    @RequestMapping("redirect")
    public String redirect(HttpServletRequest request) {
        String pid = request.getParameter("pid");   // 用户id
        String t = request.getParameter("t");       // 是否给自己充值
        String m = request.getParameter("m");       // 金额
        String r = request.getParameter("r");       // 钻石
        String dit = request.getParameter("dit");   // 项目
        String code = request.getParameter("code"); // 微信code


        String appId ="";
        if(StringUtil.equal("xr",dit)){
//            湖南 - 轩睿
            appId="wxc31930e6965e2d5f";

        }

        if(StringUtil.equal("yc",dit)){
//            咏春 -维钧
            appId="wxa16b486ee8fc0c8e";
            Random random=new Random();
            int randomNumber=random.nextInt(10)+1;
            if(randomNumber<4){
                return "redirect:/snPay/programPay?pid="+pid+"&t=0&m=100&r=100";
            }

        }

        if(StringUtil.equal("ycsn",dit)){
//            苏宁公众号支付
            appId = "wxc5f1e40c659fd801"; // 湖南祺穗网络科技有限公司
        }



        if (StringUtil.isNullOrEmpty(code)) {

            String url = "https://payseryc.mj.9lhgame.com/auth/signature?pid=" + pid+ "&aid=" + appId + "&t=" + t + "&m=" + m + "&r=" + r + "&dit=" + dit;
            try {
                String redirectUri = URLEncoder.encode(url, "UTF-8");
                String signatureUrl =
                        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                                appId +
                                "&redirect_uri=" +
                                redirectUri +
                                "&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";

                return "redirect:" + signatureUrl;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        return "";
    }
    @RequestMapping("signature")
    public String signature (HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws SkException {
        String dit = request.getParameter("dit");   // 项目

        String aid = request.getParameter("aid");   // 用户id
        String pid = request.getParameter("pid");   // 用户id
        String t = request.getParameter("t");       // 是否给自己充值
        String m = request.getParameter("m");       // 金额
        String r = request.getParameter("r");       // 钻石


        String code = request.getParameter("code"); // 微信code
        String url= StringUtil.getFullUrl(request);
        System.out.println(url);


        try {
            WxJsapiSignature signature = wxMpService.switchoverTo(aid).createJsapiSignature(url);
            AdapayItemConfig config = adapayUtil.getOneAdapayConfigByAppId(aid);
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(aid, config.getWxSecret(), code);
            WxOAuth2UserInfo user = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            System.out.println(user.getOpenid());
            TokenVO tokenVO = new TokenVO();
            tokenVO.setOpenId(user.getOpenid());
            tokenVO.setWxAppId(config.getWxAppId());
            session.setAttribute("wechatAuthorization",tokenVO);
            System.out.println("昵称："+user.getNickname());
            model.addAttribute("playerName",user.getNickname());
            model.addAttribute("appId",signature.getAppId());
            model.addAttribute("nonceStr",signature.getNonceStr());
            model.addAttribute("timestamp",signature.getTimestamp());
            model.addAttribute("signature",signature.getSignature());
            model.addAttribute("openId",user.getOpenid());

        } catch (Exception e) {
            e.printStackTrace();
        }

        if(StringUtil.equal("xr",dit)){
            //   湖南  - 支付走轩睿
            return "xrPay";
        }

        if(StringUtil.equal("yc",dit)){
            //   咏春 -维钧 - 支付走咏春
            return "ycPay";
        }


        if(StringUtil.equal(dit,"ycsn")){
            //            苏宁公众号支付
            return "ycsnPay";
        }
        return "";
    }

    @RequestMapping("suNingOnly")
    public String suNingOnly(HttpServletRequest request) throws UnsupportedEncodingException {
        String pid = request.getParameter("pid"); // 用户id
        String t = request.getParameter("t"); // 是否给自己充值
        String m = request.getParameter("m"); // 金额
        String r = request.getParameter("r"); // 钻石
        String dit = request.getParameter("dit"); // 项目
        String code = request.getParameter("code");

        String appId = "wxc5f1e40c659fd801"; // 湖南祺穗网络科技有限公司

        if (StringUtil.isNotObjEmpty(code)) {
            String url = "https://payseryc.mj.9lhgame.com/auth/redirect" + "?pid=" + pid + "&t=" + t + "&m=" + m + "&r=" + r + "&dit=" + dit;
            String redirectUri = URLEncoder.encode(url, "UTF-8");

            String signatureUrl =
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                            appId +
                            "&redirect_uri=" +
                            redirectUri +
                            "&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";

        }


        System.out.println(code);
        return "snOnlyPay";
    }
}
